<template>
  <div>
    <!-- 分配作业量 -->
    <!-- <div class="toplan">
      <span style="margin-left: 10px;">机械作业量</span>
      <div class="buttonclass">
        <el-button type="text" size="mini" @click="useTallyData">使用理货数据</el-button>
        <el-button type="text" size="mini" @click="useTicketData">使用签票数据</el-button>
      </div>
    </div> -->
    <el-form :model="amountForm" label-width="80px" class="formclass">
      <el-row>
        <el-col :span="5">
          <el-form-item label="件数:">
            <el-input v-model="amountForm.quantity" size="mini" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="重量:">
            <el-input v-model="amountForm.ton" size="mini" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="车数:">
            <el-input v-model="amountForm.carNum" size="mini" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="体积:">
            <el-input v-model="amountForm.volume" size="mini" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <baseTablecheck 
      ref="amount"
      :loading="loading"
      :data="tableData"
      :columns="columns" 
      @checkId="selectChange"
      :tableHT="tableHeight" 
      :pagination="false"></baseTablecheck>
    <!-- 劳务 -->
    <div class="toplan">
      <span style="margin-left: 10px;">劳务作业量</span>
    </div>
    <baseTable
      ref="amount"
      :loading="lloading"
      :data="ltableData"
      :columns="lcolumns"
      :tableHeight="tableHeight" 
      :pagination="false"></baseTable>
  </div>
</template>
<script>
import baseTablecheck from "@/components/BaseTable/baseTablecheck"
import baseTable from "@/components/BaseTable"
import api from '@/api/yardTally/singTicket/index'
import publicapi from "@/api/public"
export default {
  components: { baseTablecheck,baseTable },
  props: { 
    workLineInfo: {
      type: Object
    },
    ticketForm: { 
      type: Object
    },
    selectMachineClick: {
      type: Function
    },
    processList: {
      type: Array
    },
    initTicketInfo: {
      type: Function
    }
  },
  data () {
    return {
      loading: false,
      tableData: [],
      columns: [
        {
          prop: 'deptName',
          label: '作业单位',
        },
        {
          prop: 'equipmentTypeName',
          label: '机械类型',
        },
        {
          prop: 'equipmentNo',
          label: '机械编号',
        },
        {
          prop: 'positionName',
          label: '作业位置',
        },
        {
          prop: 'userNo',
          label: '司机工号',
        },
        {
          prop: 'operatorsName',
          label: '司机姓名',
        },
        {
          label: '库场',
          width: 100,
          render: (h,params) => {
            return (
              h("el-select", {
						    props: {
						    	value: params.row.storehouseId,
						    	size: "mini",
						    	placeholder: "请选择",
                  clearable: true
						    },
						    on: {
						    	change: e => {
                    console.log(e)
						    		this.$set(this.tableData[params.row.index], "storehouseId", e)
                    this.$set(this.tableData[params.row.index], "storehouseName", e?this.storehouseList.filter(v => v.id == e)[0].storehouseName:'')
						    	},
						    },
              },
              this.storehouseList.map(item => {
								return h("el-option", {
									props: {
										value: item.id,
										label: item.storehouseName,
										size: "mini",
									},
								})
							})
              )
            )
          }
        },
        {
          label: '起始区域',
          width: 120,
          render: (h,params) => {
            return (
              h("el-select", {
						    props: {
						    	value: params.row.startRegionCode,
						    	size: "mini",
						    	placeholder: "请选择",
                  clearable: true
						    },
						    on: {
						    	change: e => {
                    console.log(e)
						    		this.$set(this.tableData[params.row.index], "startRegionCode", e)
                    this.$set(this.tableData[params.row.index], "startRegionName", e?this.regionList.filter(v => v.dictValue == e)[0].dictLabel:'')
						    	},
						    },
              },
              this.regionList.map(item => {
								return h("el-option", {
									props: {
										value: item.dictValue,
										label: item.dictLabel,
										size: "mini",
									},
								})
							})
              )
            )
          }
        },
        {
          label: '终点区域',
          width: 120,
          render: (h,params) => {
            return (
              h("el-select", {
						    props: {
						    	value: params.row.endRegionCode,
						    	size: "mini",
						    	placeholder: "请选择",
                  clearable: true
						    },
						    on: {
						    	change: e => {
                    console.log(e)
						    		this.$set(this.tableData[params.row.index], "endRegionCode", e)
                    this.$set(this.tableData[params.row.index], "endRegionName", e?this.regionList.filter(v => v.dictValue == e)[0].dictLabel:'')
						    	},
						    },
              },
              this.regionList.map(item => {
								return h("el-option", {
									props: {
										value: item.dictValue,
										label: item.dictLabel,
										size: "mini",
									},
								})
							})
              )
            )
          }
        },
        {
          prop: 'carNum',
          label: '车数',
          width: 100,
          render: (h,params) => {
            return (
              h("el-input", {
						    props: {
						    	value: params.row.carNum,
						    	type: "text",
						    	size: "mini",
						    	placeholder: "请输入",
                  clearable: true
						    },
						    on: {
						    	input: e => {
                    console.log(e)
						    		this.$set(this.tableData[params.row.index], "carNum", e)
						    	},
						    },
              })
            )
          }
        },
        {
          prop: 'quantity',
          label: '件数',
          width: 100,
          render: (h,params) => {
            return (
              h("el-input", {
						    props: {
						    	value: params.row.quantity,
						    	type: "text",
						    	size: "mini",
						    	placeholder: "请输入",
                  clearable: true
						    },
						    on: {
						    	input: e => {
                    console.log(e)
						    		this.$set(this.tableData[params.row.index], "quantity", e)
						    	},
						    },
              })
            )
          }
        },
        {
          prop: 'ton',
          label: '重量',
          width: 100,
          render: (h,params) => {
            return (
              h("el-input", {
						    props: {
						    	value: params.row.ton,
						    	type: "text",
						    	size: "mini",
						    	placeholder: "请输入",
                  clearable: true
						    },
						    on: {
						    	input: e => {
                    console.log(e)
						    		this.$set(this.tableData[params.row.index], "ton", e)
						    	},
						    },
              })
            )
          }
        },
        {
          prop: 'volume',
          label: '体积',
          width: 100,
          render: (h,params) => {
            return (
              h("el-input", {
						    props: {
						    	value: params.row.volume,
						    	type: "text",
						    	size: "mini",
						    	placeholder: "请输入",
                  clearable: true
						    },
						    on: {
						    	input: e => {
                    console.log(e)
						    		this.$set(this.tableData[params.row.index], "volume", e)
						    	},
						    },
              })
            )
          }
        },
      ],
      tableHeight: 300,
      selectData: [], // 选中需要分配的机械
      lloading: false,
      ltableData: [], // 劳务
      lcolumns: [
        {
          prop: 'operatorsName',
          label: '姓名',
        },
        {
          prop: 'craftCode',
          label: '操作工艺',
          render: (h,params) => {
            return (
              h("el-select", {
						    props: {
						    	value: params.row.craftCode,
						    	size: "mini",
						    	placeholder: "请选择",
						    },
						    on: {
						    	change: e => {
                    console.log(e)
						    		this.$set(this.ltableData[params.row.index], "craftCode", e)
                    this.$set(this.ltableData[params.row.index], "craftName", this.craftList.filter(v => v.dictValue == e)[0].dictLabel)
						    	},
						    },
              },
              this.craftList.map(item => {
								return h("el-option", {
									props: {
										value: item.dictValue,
										label: item.dictLabel,
										size: "mini",
									},
								})
							})
              )
            )
          }
        },
        {
          prop: 'ton',
          label: '重量',
          render: (h,params) => {
            return (
              h("el-input", {
						    props: {
						    	value: params.row.ton,
						    	type: "text",
						    	size: "mini",
						    	placeholder: "请输入",
						    },
						    on: {
						    	input: e => {
                    console.log(e)
						    		this.$set(this.ltableData[params.row.index], "ton", e)
						    	},
						    },
              })
            )
          }
        },
        {
          prop: 'quantity',
          label: '件数',
          render: (h,params) => {
            return (
              h("el-input", {
						    props: {
						    	value: params.row.quantity,
						    	type: "text",
						    	size: "mini",
						    	placeholder: "请输入",
						    },
						    on: {
						    	input: e => {
                    console.log(e)
						    		this.$set(this.ltableData[params.row.index], "quantity", e)
						    	},
						    },
              })
            )
          }
        },
        {
          prop: 'volume',
          label: '体积',
          render: (h,params) => {
            return (
              h("el-input", {
						    props: {
						    	value: params.row.volume,
						    	type: "text",
						    	size: "mini",
						    	placeholder: "请输入",
						    },
						    on: {
						    	input: e => {
                    console.log(e)
						    		this.$set(this.ltableData[params.row.index], "volume", e)
						    	},
						    },
              })
            )
          }
        },
      ],
      craftList: [], // 操作工艺
      storehouseList: [], // 场地
      regionList: [], // 区域
      amountForm: {
        quantity: '',
        ton: '',
        carNum: '',
        volume: '',
      }
    }
  },
  watch: {
    ticketForm: {
      handler(value) {
        console.log(value)
        this.searchAmount()
      },
      deep: true
    }
  },
  mounted () {
    this.getDictList()
    this.getStorehouse()
  },
  methods: {
    // 查询字典
    getDictList () {
      publicapi.getDictData('CRAFT,REGION').then(res => {
        this.craftList = res.data.data.CRAFT
        this.regionList = res.data.data.REGION
      })
    },
    // 查询库场
    getStorehouse () {
      publicapi.listStorehouse().then(res => {
        this.storehouseList = res.data.data
      })
    },
    // 切换过程查询数据
    searchAmount () {
      this.selectEquipment() // 查询机械
      this.selectWorker() // 查询劳务
      this.selectAllData() // 查询汇总数据
    },
    // 查询机械
    selectEquipment () {
      let params = {
        planId: this.workLineInfo.id,
        ticketId: this.ticketForm.id
      }
      api.selectEquipment(params).then(res => {
        this.tableData = res.data.data
        this.$refs.amount.clearSelection()
      })
    },
    // 查询劳务
    selectWorker () {
      let params = {
        planId: this.workLineInfo.id,
        ticketId: this.ticketForm.id
      }
      api.selectWorker(params).then(res => {
        this.ltableData = res.data.data
      })
    },
    // 查询汇总数据
    selectAllData () {
      this. amountForm = {
        quantity: '',
        ton: '',
        carNum: '',
        volume: '',
      }
      let params = {
        id: this.ticketForm.id
      }
      api.selectTYardTicketNumByTicket(params).then(res => {
        if (res.data.code != '0000') {
          return this.$message.error(res.data.msg)
        }
        this.amountForm = res.data.data
      })
    
    },
    // 使用理货数据
    useTallyData () {
      let params = {
        planId: this.workLineInfo.id,
        processCode: this.ticketForm.processCode,
        cargoInfoId: this.ticketForm.cargoInfoId,
      }
      api.selectYardTallyByEquipmentNo(params).then(res => {
        if (res.data.code != '0000') {
          return this.$message.error(res.data.msg)
        }
        this.tableData = res.data.data
        this.$refs.amount.clearSelection()
      })
      api.selectYardTallyTotal(params).then(res => {
        if (res.data.code != '0000') {
          return this.$message.error(res.data.msg)
        }
        this.amountForm = res.data.data
        this.allocationLabourAmount()
      })
    },
    // 选中需要分配的机械
    selectChange (val) {
      this.selectData = []
      this.selectData = val
    },
    // 使用签票数据
    useTicketData () {
      if (this.selectData.length == 0) {
        return this.$message.warning('请先勾选需要分配的机械')
      }
      
      this.tableData.forEach(val => {
        val.volume = ''
        val.quantity = ''
        val.ton = ''
        val.carNum = ''
      })

      var volume = Number(this.ticketForm.volume)
      var quantity = Number(this.ticketForm.quantity)
      var ton = Number(this.ticketForm.ton)
      var carNum = Number(this.ticketForm.carNum)

      // this.selectData.forEach(v => {
      //   this.tableData.forEach(item => {
      //     if (v.equipmentId == item.equipmentId) {
      //       item.flag = true
      //     }
      //   })
      // })

      const obj = this.selectData.reduce((obj,key)=>{
        if (key.position in obj){
          obj[key.position]++
        } else {
          obj[key.position]=1
        }
        return obj
      }, {})
      console.log(obj);
      this.selectData.forEach(item => {
        let quantity1 = Number(quantity/obj[item.position]).toFixed(1).split('.')[1]
        if (quantity1 > 0) {
          item.quantity = Number(quantity/obj[item.position]).toFixed(1)
        } else {
          item.quantity = Number(quantity/obj[item.position])
        }
        let carNum1 = Number(carNum/obj[item.position]).toFixed(1).split('.')[1]
        if (carNum1 > 0) {
          item.carNum = Number(carNum/obj[item.position]).toFixed(1)
        } else {
          item.carNum = Number(carNum/obj[item.position])
        }
        item.ton = Number(ton/obj[item.position]).toFixed(3)
        item.volume = Number(volume/obj[item.position]).toFixed(3)
      })

      // 劳务
      var llength = this.ltableData ? this.ltableData.length : 0
      if (llength) {
        this.ltableData.forEach(v => {
          v.ton = Number(ton/llength).toFixed(3)
          v.volume = Number(volume/llength).toFixed(3)
          if (this.workLineInfo.cargoCategoryCode.substring(0,2) !== '07') {
            v.quantity = Number(quantity/llength)
          }
        })
      }

      // this.selectMachineClick(this.selectData)
    },
    // 使用返回的总量为劳务分配数据
    allocationLabourAmount () {
      var ton = this.amountForm.ton
      var quantity = this.amountForm.quantity
      var volume = this.amountForm.volume
      var llength = this.ltableData ? this.ltableData.length : 0
      if (llength) {
        this.ltableData.forEach(v => {
          v.ton = Number(ton/llength).toFixed(3)
          v.volume = Number(volume/llength).toFixed(3)
          if (this.workLineInfo.cargoCategoryCode.substring(0,2) !== '07') {
            v.quantity = Number(quantity/llength)
          }
        })
      }
    },
    // 保存作业量
    submitAmount () {
      var num = 0
      this.tableData.forEach(val => {
        if (String(val.quantity).indexOf('.') > -1) {
          num++
        }
        if (String(val.carNum).indexOf('.') > -1) {
          num++
        }
      })
      if (num > 0) {
        return this.$message.warning('车数/件数存在小数,请调整后再保存')
      }

      num = 0
      this.ltableData.forEach(v => {
        if (!v.craftCode)
          num++
      })
      if (num > 0) {
        return this.$message.warning('劳务请选择操作工艺')
      }
      let params = {
        id: this.ticketForm.id,
        planId: this.workLineInfo.id,
        ticketId: this.ticketForm.id,
        cargoInfoId: this.ticketForm.cargoInfoId,
        shipvoyageId: this.workLineInfo.shipvoyageId,
        workDate: this.workLineInfo.workDate,
        workTime: this.workLineInfo.workTime,
        processCode: this.ticketForm.processCode,
        processName: this.processList.filter(v => v.processCode == this.ticketForm.processCode)[0]. processName,
        quantity: this.amountForm.quantity,
        ton: this.amountForm.ton,
        carNum: this.amountForm.carNum,
        volume: this.amountForm.volume,
        sharePOList: this.tableData,
        workerList: this.ltableData
      }
      api.addTYardTicketShare(params).then(res => {
        if (res.data.code != '0000') {
          return this.$message.error(res.data.msg)
        }
        // 刷新新增的子过程
        this.initTicket()
        this.$message.success('保存成功')
      })
    },
    initTicket () {
      this.initTicketInfo(1)
    },
    // 新增签票
    insertTicket () {
      this.ticketForm.id = ''
      this.selectEquipment()
    },
  }
}
</script>
<style lang="less" scoped>
.toplan {
  height: 40px;
  line-height: 40px;
  width: 100%;
  background-color: #f5f7fa;
}
.buttonclass {
  float: right;
}
.formclass {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>